package org.dallasrowing.logbook.ui.controller;

import java.util.Date;
import java.util.List;

import org.dallasrowing.logbook.ui.view.LogBookWindow;
import org.dallasrowing.logbook.ui.view.SignOutWindow;
import org.dallasrowing.logbook.util.FormatUtil;
import org.dallasrowing.model.LogBookEntry;
import org.dallasrowing.model.dao.DAOException;
import org.dallasrowing.model.dao.LogBookDAO;

public class SignOutWindowControllerImpl implements SignOutWindowController {

	private LogBookDAO logBookDAO;
	private LogBookWindow mainWindow;
	private SignOutWindow signOutWindow;

	public SignOutWindowControllerImpl(LogBookWindow mainWindow, LogBookDAO logBookDAO) {
		this.logBookDAO = logBookDAO;
		this.mainWindow = mainWindow;
	}

	public void newSignOutWindow(SignOutWindow signOutWindow) {
		this.signOutWindow = signOutWindow;
	}

	public void openSignOutWindow(LogBookUiController parentController) {
		fillWindowData();
		registerListeners(parentController);
	}

	private void registerListeners(final LogBookUiController parentController) {
		this.signOutWindow.setSubmitButtonListener(new Runnable() {
		
			public void run() {
				signOutSubmitted();
			}
		
		});
	}

	protected void signOutSubmitted() {
		LogBookEntry entry = signOutWindow.getSelectedOpenEntry();
		String entryCloseDateString = signOutWindow.getCloseEntryDate();
		String milesRowedString = signOutWindow.getMilesRowed();
		String comment = signOutWindow.getComment();
		
		try {
			Date entryCloseDate = FormatUtil.parseDate(entryCloseDateString);
			Double distanceRowed = Double.valueOf(milesRowedString);

			entry.setEntryCloseDate(entryCloseDate);
			entry.setDistanceRowed(distanceRowed);
			entry.setComment(comment);
		
			logBookDAO.update(entry);
			
			signOutWindow.closeWindow();
			
		} catch (Exception e) {
			mainWindow.showError(e);
		}
	}

	private void fillWindowData() {
		try {
			List<LogBookEntry> logBookEntries = logBookDAO.findOpenEntriesSortByDate();
			signOutWindow.updateOpenEntriesList(logBookEntries);
		} catch (DAOException e) {
			mainWindow.showError(e);
		}
	}

}
